import * as React from 'react';

import {IDesign} from '../../types/IDesign';
import {IView} from '../../types/IView';
import isParentView, {IParentView} from '../../types/IParentView';
import HierarchyNode, {HierarchyNodeProps} from './HierarchyNode';

import './HierarchyPane.css';

export interface HierarchyPaneProps {
  design: IDesign;
  selectedView: IView;
}

export interface HierarchyPaneState {
  viewExpandState: {
    [viewId: string]: boolean;
  };
}

class HierarchyPane extends React.Component<HierarchyPaneProps, HierarchyPaneState> {

  constructor(props: HierarchyPaneProps) {
    super(props);

    this.state = {
      viewExpandState: {}
    };
  }

  render() {
    const {design} = this.props;

    return (
      <div className="Hierarchy">
        <div className="Hierarchy-title">组件层次</div>
        <div className="Hierarchy-content">
          {this.renderParentView(design.root)}
        </div>
      </div>
    );
  }

  private renderView(view: IView) {
    if (isParentView(view)) {
      return this.renderParentView(view);
    }

    return (
      <div key={view.id} className="Hierarchy-item">
        {this.renderNode(view)}
      </div>
    );
  }

  private renderParentView(view: IParentView) {
    const parentViewClass = view.children.length > 0 ? 'Hierarchy-item-parent' : '';
    const viewStateClass = this.state.viewExpandState[view.id] ? 'expanded' : '';
    const viewClass = `Hierarchy-item ${parentViewClass} ${viewStateClass}`;
    return (
      <div key={view.id} className={viewClass}>
        {this.renderNode(view)}
        <div className="Hierarchy-item-children">
          {view.children.map(childView => this.renderView(childView))}
        </div>
      </div>
    );
  }

  private renderNode(view: IView) {
    const nodeProps: HierarchyNodeProps = {
      view,
      selectedView: this.props.selectedView,
      isExpanded: this.state.viewExpandState[view.id],
      onToggle: this.handleToggle
    };
    return (
      <HierarchyNode {...nodeProps}/>
    );
  }

  private handleToggle = (view: IView) => {
    const viewExpandState = {...this.state.viewExpandState};
    viewExpandState[view.id] = !viewExpandState[view.id];
    this.setState({...this.state, viewExpandState});
  }
}

export default HierarchyPane;
